// -----------------------------------------------
// Author:     code34 nicolas_boiteux@yahoo.fr
// Edited by:  Neumatic
// Warcontext: Respawn vehicle at their original position
// -----------------------------------------------
if (!isServer) exitWith {};

private [
	"_vehicle",
	"_delay",
	"_startpos",
	"_startdir",
	"_type",
	"_disabled",
	"_vehiclename",
	"_move",
	"_name",
	"_objets_charges"
];

_vehicle = _this select 0;
_delay   = _this select 1;

if (format ["%1", _vehicle] == "any") exitWith {};

_startpos = getPosATL _vehicle;
_startdir = getDir _vehicle;
_type = typeOf _vehicle;
_vehiclename = vehicleVarName _vehicle;
_move = 0;

if (wcwithrandomfuel == 1) then {
	_vehicle setFuel random 0.5;
	_vehicle setVehicleAmmo random 0.5;
};

WC_fnc_initializevehicle = {
	private ["_vehicle"];

	_vehicle = _this select 0;

	_vehicle removeAllEventHandlers "HandleDamage";
	_vehicle addEventHandler ["HandleDamage", {
		if (_this select 2 > wcdammagethreshold) then {
			(_this select 0) removeAllEventHandlers "HandleDamage";
			if ((_this select 2) + (getDammage (_this select 0)) > 0.9) then {
				(_this select 0) setDamage 1;
			} else {
				(_this select 0) setDamage ((getDammage (_this select 0)) + (_this select 2));
			};
		}
	}];

	_vehicle addEventHandler ["Fired", {
		private ["_name"];
		if !(wcdetected) then {
			if ((getMarkerPos "rescue") distance (position player) < 400) then {
				wcalerttoadd = ceil(random 10);
				["wcalerttoadd", "server"] call WC_fnc_publicvariable;
			};
		};
		wcammoused = wcammoused + 1;
	}];
};

[_vehicle] call WC_fnc_initializevehicle;

// If simulation vehicles not respawn
if (wckindofgame == 2) exitWith {};

//A3 TODO: Redo script; Maybe 1 loop for all vehicles
while {true} do {
	if (count (crew _vehicle) == 0) then {
		_move = _move + 1;
		_disabled = (if (damage _vehicle > 0.9) then {true} else {false});
		if (_disabled || !(alive _vehicle) || ((_move > 1800) and (getPos _vehicle distance _startpos > 10))) then {
			sleep wctimetorespawnvehicle;
			_vehicle setPos [0,0,0];
			_vehicle setDamage 1;
			_objets_charges = _vehicle getVariable "R3F_LOG_objets_charges";
			clearVehicleInit _vehicle;
			deleteVehicle _vehicle;
			sleep 0.5;
			_vehicle = _type createVehicle _startpos;
			_vehicle setPosATL _startpos;
			_vehicle setDir _startdir;
			_vehicle setVehicleVarName _vehiclename;
			//_vehicle setVehicleInit format ["this setVehicleVarName '%1';", _vehiclename];
			processInitCommands;
			_vehicle setVariable ["R3F_LOG_objets_charges", _objets_charges, true];
			_move = 0;
			_name = getText (configFile >> "CfgVehicles" >> _type >> "DisplayName");
			diag_log format ["WARCONTEXT: RESPAWN VEHICLE %1", _name];
			[_vehicle] call WC_fnc_initializevehicle;
		};
	}else{
		_move = 0;
	};
	sleep 1;
};